package org.benjamin.tenancy.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.benjamin.tenancy.domain.BuildingForm;
import org.benjamin.tenancy.domain.entity.Building;
import org.benjamin.tenancy.domain.entity.Housing;
import org.benjamin.tenancy.repository.BuildingRepository;
import org.benjamin.tenancy.repository.HousingRepository;
import org.benjamin.tenancy.service.BuildingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service
public class BuildingServiceImpl implements BuildingService {
	
	private BuildingRepository buildingRepository;
	
	private HousingRepository housingRepository;
	
	@Override
	public void analyseAndSave(BuildingForm buildingForm){
		Building building = new Building();
		building.setName(buildingForm.getName());
		this.buildingRepository.save(building);
		
		List<Housing> housings = new ArrayList<>();
		for(int row = 1 ;row <= buildingForm.getLayerNumber();row++){
			for(int space = 1;space <= buildingForm.getLayerSpace();space++ ){
				Housing housing = new Housing();
				DecimalFormat decimalFormat = new DecimalFormat("00");
				housing.setNumber(row+""+decimalFormat.format(space));
				housings.add(housing);
			}
		}
		this.housingRepository.save(housings);
		building.getHousings().addAll(housings);
		this.buildingRepository.save(building);
	}

	@Override
	public List<Building> findBuildingByUser(String username,boolean housingLoad) {
		List<Building> buildings = this.buildingRepository.findAll();
		if(housingLoad){
			for(Building building :buildings){
				//Hibernate.initialize(building.getHousings());
				Sort sort = new Sort("number");
				List<Housing> housings = this.housingRepository.findByBuildingId(building.getId(), sort);
				building.setHousings(housings);
			}
		}
		return buildings;
	}

}
